/*
 * 通讯录导出
 */
package address;

import static address.BeginPanel.getContNum;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Mavis
 */
public class ImportCon extends JFrame {

    //导入新通讯录的联系人信息
    ArrayList Contacts = new ArrayList();
    //原有的通讯录的联系人信息
    ArrayList contacts = new ArrayList();
    //原有通讯录的分组信息
    ArrayList belongs = new ArrayList();
    Font f = new Font("微软雅黑", Font.PLAIN, 20);
    Font f2 = new Font("微软雅黑", Font.PLAIN, 16);
    Font f3 = new Font("微软雅黑", Font.PLAIN, 12);
    public ImportCon(ArrayList contacts, ArrayList belongs) {
        setLayout(null);
        this.contacts = contacts;
        this.belongs = belongs;
        importConPanel importPanel = new importConPanel();
        add(importPanel);
        importPanel.setBounds(0, 0, 300, 300);
        importPanel.setBackground(Color.white);
        importPanel.setFocusable(true);

    }

    private class importConPanel extends JPanel {

        //导入通讯录面板
        JPanel p = new JPanel();
        //导入类型选择面板（选择是否覆盖导入）
        JPanel selectStylePanel = new JPanel();
        JLabel label1 = new JLabel("* 遇到重复记录：");
        JLabel label2 = new JLabel("* 选择需要导入的文件");
        //选择导入文件的按钮
        JButton jbtSelectFile = new JButton("选择文件");
        //选择导入形式为覆盖导入的单选按钮
        JRadioButton jrbCover = new JRadioButton(" 覆盖 ");
        //选择导入形式为不覆盖导入的单选按钮
        JRadioButton jrbnotCover = new JRadioButton(" 不覆盖");

        //需要被导入的文件
        File file = null;

        public importConPanel() {
            setLayout(null);

            //设置导入面板的参数
            p.setBounds(0, 0, 300, 300);
            //设置导入面板底色为白色
            p.setBackground(Color.white);
            p.setLayout(null);
            add(p);

            //设置label1的参数
            label1.setBounds(10, 10, 200, 30);
            label1.setFont(f3);
            label1.setOpaque(false);
            p.add(label1);

            //设置导入形式单选按钮的参数
            jrbCover.setBounds(40, 45, 100, 30);
            jrbCover.setOpaque(false);
            jrbCover.setFont(f);
            p.add(jrbCover);

            jrbnotCover.setBounds(140, 45, 100, 30);
            jrbnotCover.setOpaque(false);
            jrbnotCover.setFont(f);
            p.add(jrbnotCover);

            ButtonGroup group = new ButtonGroup();
            group.add(jrbCover);
            group.add(jrbnotCover);

            //设置label2的参数
            label2.setBounds(10, 80, 250, 30);
            label2.setOpaque(false);
            label2.setFont(f3);
            p.add(label2);

            //为导入文件按钮注册监听器
            selectFileListener listener1 = new selectFileListener();
            //设置导入文件的按钮
            jbtSelectFile.setBounds(50, 122, 180, 50);
            jbtSelectFile.setBackground(Color.white);
            jbtSelectFile.setFont(f);
            jbtSelectFile.addActionListener(listener1);
            p.add(jbtSelectFile);

            jbtOKListener listener2 = new jbtOKListener();
            //设置确定按钮的参数
            ImageIcon Icon1 = new ImageIcon("img/confirm.png");   
            JButton jbtOK = new JButton(Icon1);   
            jbtOK.setBorderPainted(false);                  
            jbtOK.setBounds(25, 200, 100, 30);
  
            jbtOK.addActionListener(listener2);
            p.add(jbtOK);

            //设置取消按钮的参数
            ImageIcon Icon2 = new ImageIcon("img/cancel_newPeople.png");   
            JButton jbtCancel = new JButton(Icon2);   
            jbtCancel.setBorderPainted(false);  
            jbtCancel.setBounds(155, 200, 100, 30);
   
            //取消按钮添加监听器，当取消按钮被监听到时，不导入通讯录，并返回主界面
            jbtCancel.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    BeginPanel frame = new BeginPanel(contacts, belongs);
                    frame.setSize(900, 700);
                    frame.setTitle("欢迎使用通讯录管理系统");
                    frame.setLocationRelativeTo(null);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setVisible(true);
                    dispose();
                }

            });
            p.add(jbtCancel);
        }

        //选择导入文件的监听器，被监听到时打开一个文件对话框，选择需要被导入的文件，Path记录该文件的路径
        private class selectFileListener implements ActionListener {

            public selectFileListener() {
            }

            @Override
            public void actionPerformed(ActionEvent ae) {

                String saveType[] = {"vCard", "CSV"};
                JFileChooser chooser = new JFileChooser();
                chooser.setFileFilter(new FileNameExtensionFilter("vCard or CSV File", saveType));
                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    file = chooser.getSelectedFile();

                }
            }
        }

        //确认按钮的监听器，该按钮被监听到时，根据已选的导入方式导入通讯录，然后返回主界面
        private class jbtOKListener implements ActionListener {

            public jbtOKListener() {
            }

            @Override
            public void actionPerformed(ActionEvent ae) {
                //判断是否已选择导入方式（是否覆盖相同通讯记录）
                if (jrbCover.isSelected() || jrbnotCover.isSelected()) {
                    //判断是否已经选择了需要被导入的文件
                    if (file.exists()) {
                        //导入的通讯录信息先暂时放在线性表Contacts中
                        ObjectInputStream input = null;
                        try {
                            input = new ObjectInputStream(new FileInputStream(file));
                            try {
                                for (int i = 0; i < getContNum(file); i++) {
                                    People p = (People) (input.readObject());
                                    Contacts.add(p);
                                }
                            } catch (ClassNotFoundException ex) {
                                Logger.getLogger(ImportCon.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null, "导入通讯录出现错误!", "注意", JOptionPane.INFORMATION_MESSAGE);
                        }

                        //根据导入通讯录的方式把Contacts的信息添加到contacts中，并修改belongs的信息
                        //导入方式为覆盖
                        if (jrbCover.isSelected()) {                           
                            for (int i = 0; i < Contacts.size(); i++) {
                                int j;
                                People people1 = (People) Contacts.get(i);
                                for(j=0;j<contacts.size();j++){
                                    People people2=(People)contacts.get(j);
                                    if(people1.equals(people2)){
                                        break;
                                    }
                                }
                                if(j==contacts.size()){
                                    contacts.add(people1);
                                }
                            }
                        }
                            //导入方式为不覆盖相同通讯信息
                            if (jrbnotCover.isSelected()) {
                                for (int i = 0; i < Contacts.size(); i++) {
                                    People people = (People) Contacts.get(i);
                                    contacts.add(people);
                                }
                            }
                            //更新belongs的内容
                            for (int i = 0; i < contacts.size(); i++) {
                                People people = (People) contacts.get(i);
                                for (int j = 0; j < people.belongs.size(); j++) {
                                    String s = (String) people.belongs.get(j);
                                    if (!belongs.contains(s)) {
                                        belongs.add(s);
                                    }
                                }
                            }

                            BeginPanel frame = new BeginPanel(contacts, belongs);
                            frame.setSize(900, 700);
                            frame.setTitle("欢迎使用通讯录管理系统");
                            frame.setLocationRelativeTo(null);
                            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                            frame.setVisible(true);
                            dispose();

                        }
                     else {
                        JOptionPane.showMessageDialog(null, "请选择需要被导出的文件", "注意", JOptionPane.INFORMATION_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "请选择文件导出的方式", "注意", JOptionPane.INFORMATION_MESSAGE);
                }
            }

            private int getContNum(File file) throws ClassNotFoundException {
                int n = 0;
                ObjectInputStream input = null;

                try {
                    input = new ObjectInputStream(new FileInputStream(file));
                    while (true) {
                        People people= (People) (input.readObject());
                        n++;
                    }
                } catch (IOException ex) {
                    return n;
                }
            }
        }
    }

}
